/*
* @Date: 2021/3/6
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import React from 'react';
import './index.scss';

export default class extends React.Component {
  constructor(props) {
    super(props);
    this.ref = React.createRef();
  }
  onTouchStart = (e) => {
    this.isTouched = true;
    this.isScroll = false;
    this.touchStartX = e.touches[0].clientX;
  }

  scroll(dom, step, count) {
    dom.scrollLeft += step;
    count--;
    if (count === 0) {
      this.isScroll = false;
    } else {
      setTimeout(() => {
        this.scroll(dom, step, count);
      }, 50);
    }
  }

  onTouchMove = (e) => {
    const touchX = e.touches[0].clientX;
    const style = getComputedStyle(e.currentTarget);
    const width = Number(style.width.replace('px', ''));
    if (this.isTouched && !this.isScroll) {
      this.isScroll = true;
      const step = Math.round(width / 5);
      if (
        touchX - this.touchStartX < -5
        && e.currentTarget.scrollLeft < e.currentTarget.scrollWidth - width
      ) {
        this.scroll(e.currentTarget, step, 5);
      } else if (
        touchX - this.touchStartX > 10
        && e.currentTarget.scrollLeft > 0
      ) {
        this.scroll(e.currentTarget, -step, 5);
      }
      this.touchStartX = touchX;
    }
  }

  onTouchEnd = () => {
    this.isTouched = false;
  }

  render() {
    const { className = '', children, style = {} } = this.props;
    return (
      <div
        style={style}
        className={`${className} swiper-wrapper`}
        onTouchStart={this.onTouchStart}
        onTouchMove={this.onTouchMove}
        onTouchEnd={this.onTouchEnd}
      >
        { children }
      </div>
    )
  }
}
